package com.zhongli.devplatform.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongli.devplatform.bean.SecurityUser;
import com.zhongli.devplatform.mapper.sys.ReadRoleMapper;
import com.zhongli.devplatform.mapper.user.ReadUserInfoMapper;
import com.zhongli.devplatform.mapper.user.ReadUserMapper;
import com.zhongli.devplatform.po.user.ReadRolePO;
import com.zhongli.devplatform.po.user.ReadUserInfoPO;
import com.zhongli.devplatform.po.user.ReadUserPO;
import com.zhongli.devplatform.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户认证、权限
 * @author: WuXiCheng
 */
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ReadRoleMapper roleMapper;

    @Autowired
    private ReadUserMapper readUserMapper;

    @Autowired
    private ReadUserInfoMapper userInfoMapper;

    /**
     *若使用security表单鉴权则需实现该方法，通过accountNum获取用户信息（密码、权限等等）
     * @param accountNum
     * @return
     * @throws UsernameNotFoundException
     */
    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String accountNum) throws UsernameNotFoundException {
        ReadUserPO readUserPO = readUserMapper.selectOne(new QueryWrapper<ReadUserPO>().eq("account_num",accountNum));
        if (readUserPO == null){
             throw new UsernameNotFoundException("用户不存在");
        }
        ReadUserInfoPO readUserInfoPO = userInfoMapper.selectOne(new QueryWrapper<ReadUserInfoPO>().eq("user_id",readUserPO.getId()));
        if (readUserInfoPO == null){
            throw new UsernameNotFoundException("用户信息不存在");
        }
        List<ReadRolePO> readRolePOS = roleMapper.selectList(new QueryWrapper<ReadRolePO>().inSql("id",
                "select role_id from read_user_role where user_id =" + readUserPO.getId()));
        //开始授权
        String roles = StringUtils.join(readRolePOS);
        List<SimpleGrantedAuthority> authorities = getAuthorities(roles);
        //设置当前用户所需信息
        SecurityUser customUser = new SecurityUser(readUserPO.getAccountNum(), readUserPO.getPassword(), authorities);
        customUser.setId(readUserPO.getId());
        customUser.setInfoId(readUserInfoPO.getId());
        customUser.setAccountNum(readUserPO.getAccountNum());
        log.info("用户{}验证通过",accountNum);
        return customUser;
    }

    private List<SimpleGrantedAuthority> getAuthorities(String roles) {
        String[] authorities = roles.split(",");
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (String role : authorities) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role));
        }
        return simpleGrantedAuthorities;
    }


}
